import { Service } from 'egg';
import * as utils from './../utils/utils';

const crypto = require('crypto');
class UserService extends Service {
  async userLogin(userInfo:{username:string, password:string}) {
    console.log('登录用户', userInfo);
    const reMsg:{
      code:string,
      message:string,
    } = {
      code: '400',
      message: '',
    };
    // 根据用户名查找该用户名的用户信息
    // const searchUser = await this.app.mysql.get('users', { username: userInfo.username });
    const searchUser = await this.app.mysql.get('users', { username: userInfo.username });
    console.log('查询结果', searchUser);
    if (userInfo && userInfo.password && userInfo.username) {
      searchUser ? (await this.checkPassword(userInfo.password, searchUser.password) ? reMsg.code = '200' : reMsg.code = '400') : reMsg.message = '用户不存在，请注册';
    } else {
      reMsg.code = '400';
    }
    if (reMsg.code === '400') {
      return {
        ...reMsg,
      };
    } return {
      code: 200,
      msg: '登录成功',
      menu: [{
        title: '工作台',
        path: '/home',
        icon: 'el-icon-house',
        children: [],
      }, {
        title: '借贷管理',
        path: '/debitManage',
        icon: 'el-icon-money',
        children: [{
          title: '新增借款',
          path: '/debitManage/addDebitItem',
          children: [],
        }, {
          title: '新标维护',
          path: '/debitManage/upholdNewBidItems',
          children: [],
        }, {
          title: '借款审核',
          path: '/debitManage/firstLevelAuditItems',
          children: [],
        }, {
          title: '标的上架',
          path: '/debitManage/secondBidsGroundItems',
          children: [],
        }, {
          title: '进行中的标管理',
          path: '/debitManage/runningBidsItems',
          children: [],
        }, {
          title: '满标复审',
          path: '/debitManage/reexAuditItems',
          children: [],
        }, {
          title: '所有借款标',
          path: '/debitManage/debitItems',
          children: [],
        }, {
          title: '投资记录',
          path: '/debitManage/investRecords',
          children: [],
        }, {
          title: '借款标类别',
          path: '/debitManage/debitCategory',
          children: [],
        }],
      }, {
        title: '还款管理',
        path: '/repaymentManage',
        icon: 'el-icon-bank-card',
        children: [{
          title: '管理还款项',
          path: '/repaymentManage/repaymentItems',
          children: [],
        },
        {
          title: '还款记录',
          path: '/repaymentManage/repaymentRecords',
          children: [],
        },
        ],
      }, {
        title: '资金管理',
        path: '/capitalManage',
        icon: 'el-icon-wallet',
        children: [{
          title: '充值记录',
          path: '/capitalManage/reChargeLog',
          children: [],
        }, {
          title: '提现记录',
          path: '/capitalManage/withDrawMoneyLog',
          children: [],
        }, {
          title: '提现审核',
          path: '/capitalManage/withDrawCon',
          children: [],
        }, {
          title: '用户资金',
          path: '/capitalManage/userCapital',
          children: [],
        }, {
          title: '资金日志',
          path: '/capitalManage/capitalLog',
          children: [],
        }, {
          title: '平台资金',
          path: '/capitalManage/platformCapitalLog',
          children: [],
        },
        ],
      }, {
        title: '会员管理',
        path: '/memberManage',
        icon: 'el-icon-user-solid',
        children: [{
          title: '新增借款用户',
          path: '/memberManage/addDebitUser',
          children: [],
        },
        {
          title: '投资用户管理',
          path: '/memberManage/investUserManage',
          children: [],
        },
        {
          title: '借款用户管理',
          path: '/memberManage/debitUserManage',
          children: [],
        },
        ],
      }, {
        title: '内容管理',
        path: '/contentManage',
        icon: 'el-icon-s-grid',
        children: [{
          title: '轮播管理',
          icon: 'el-icon-document-copy',
          path: '/contentManage/sliderManage',
          children: [{
            title: '新增轮播',
            path: '/contentManage/sliderManage/addSliderItem',
            children: [],
          },
          ],
        },
        {
          title: '文章管理',
          icon: 'el-icon-document-copy',
          path: '/contentManage/articleManage',
          children: [
            {
              title: '新增文章',
              path: '/contentManage/articleManage/addArticleItem',
              children: [],
            },

          ],
        },
        {
          title: '意见反馈',
          icon: 'el-icon-document-copy',
          path: '/contentManage/feedBack',
          children: [
            {
              title: '反馈处理',
              path: '/contentManage/feedbackManage/addFeedbackItem',
              children: [],
            },
          ],
        },
        ],
      }],
      token: '1234567899',
      userInfo: searchUser,
    };
  }
  async addUser(userInfo:any) {
    const obj:any = JSON.parse(JSON.stringify(userInfo));
    obj.password = await this.createPassword(obj.password);
    // 1.查询该用户是否存在
    const isExist = (await this.app.mysql.select('users', {
      where: {
        username: obj.username,
      },
    })).length;
    console.log(isExist);
    let resMsg:any;
    isExist ? resMsg = {
      code: 400,
      msg: '用户已存在',
    } : (await this.app.mysql.insert('users', {
      username: obj.username,
      name: '王二虎',
      password: obj.password,
    })).affectedRows > 0 ? resMsg = {
        code: 200,
        msg: '添加用户成功',
      } : resMsg = {
        code: 203,
        msg: '添加用户失败，服务器异常',
      };
    return {
      ...resMsg,
    };
  }
  async updateUser(userInfo:object) {
    const obj:any = JSON.parse(JSON.stringify(userInfo));
    let res:any = {};
    try {
      res = await this.app.mysql.update('users', {
        password: await this.createPassword(obj.info.password),
        username: obj.info.username,
        uid: obj.info.uid,
        salt: obj.info.salt,
        email: obj.info.email,
      }, {
        where: {
          id: obj.id,
        },
      });
    } catch (e) {
      res = e;
      return {
        code: 500,
        msg: '数据库出错',
      };
    }
    console.log(res);
    if (res.affectedRows > 0) {
      return {
        code: 200,
        msg: '用户信息修改成功',
        updateTime: utils.getNowTime(),
      };
    }
    return {
      code: 400,
      msg: '修改失败，参数有误',
    };
  }
  async createPassword(password:string) {
    const { ctx } = this;
    console.log(ctx.app.config.cryptoConfig.secret, password);
    const hmac = crypto.createHash('sha256', ctx.app.config.cryptoConfig.secret);
    hmac.update(password);
    return hmac.digest('hex');
  }
  // 验证密码
  async checkPassword(password:string, hash_password:string) {
    // 先对需要验证的密码进行加密
    password = await this.createPassword(password);
    return password === hash_password;
  }
}

module.exports = UserService;
